<?php

declare(strict_types=1);

namespace App\Controller\Admin;

use App\Constants\ErrorCode;
use App\Model\Admin\Admin;
use App\Model\ChargeOption;
use App\Model\Device;
use App\Model\Station;
use Hyperf\DbConnection\Db;
use Hyperf\Redis\Redis;
use Hyperf\HttpServer\Contract\RequestInterface;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\SimpleCache\InvalidArgumentException;
use RedisException;
use Trait\ResponseMsg;
use App\Model\Normal;
use Hyperf\Di\Annotation\Inject;
use Util\Common;
use App\Controller\AbstractController;
use App\Model\Distributors;

class StationController extends AbstractController
{
    use ResponseMsg;

    protected Redis $redis;
    protected Normal $normal;

    #[Inject]
    protected Station $station;

    #[Inject]
    protected ChargeOption $chargeOption;

    #[Inject]
    protected Distributors $distributors;

    #[Inject]
    protected Device $device;

    public function __construct()
    {
        $this->redis = container()->get(Redis::class);
        $this->normal = container()->get(Normal::class);
    }

    /**电站列表
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function getList(RequestInterface $request):ResponseInterface
    {
        $page = $request->inputs(['page','limit','keyword','charge_id','distributor_id','is_active']);
        $page['info'] = $this->distributors->getInfo($request);
        $data['list'] = $this->station->where(function ($query) use ($page) {
            if (array_key_exists('keyword',$page) && $page['keyword']) {
                $query->where('name', 'like', '%' . $page['keyword'] . '%');
                $query->orWhere('address', 'like', '%'.$page['keyword'].'%');
            }
            if($page['is_active'] != ''){
                $query->where('is_active', $page['is_active']);
            }
            if($page['distributor_id']){
                $page['distributor_id'] = json_decode($page['distributor_id']);
                $query->where('distributor_id', end($page['distributor_id']));
            }else{
                if($page['info']['level'] == 2){
                    $query->where('distributor_id', $page['info']['id']);
                }else{
                    $distributors = Distributors::where('parent_id',$page['info']['id'])
                        ->orWhere('id',$page['info']['id'])->pluck('id')->toArray();
                    $query->whereIn('distributor_id',$distributors);
                }
            }
        })->with('distributors')
            ->withCount('device')
            ->orderBy('id', 'desc')
            ->offset(($page['page'] - 1) * $page['limit'])
            ->limit($page['limit'])
            ->get()->toArray();
        $data['total']= $this->station->where(function ($query) use ($page) {
            if (array_key_exists('keyword',$page) && $page['keyword']) {
                $query->where('name', 'like', '%' . $page['keyword'] . '%');
                $query->orWhere('address', 'like', '%'.$page['keyword'].'%');
            }
            if($page['is_active'] != ''){
                $query->where('is_active', $page['is_active']);
            }
            if($page['distributor_id']){
                $page['distributor_id'] = json_decode($page['distributor_id']);
                $query->where('distributor_id', end($page['distributor_id']));
            }else{
                if($page['info']['level'] == 2){
                    $query->where('distributor_id', $page['info']['id']);
                }else{
                    $distributors = Distributors::where('parent_id',$page['info']['id'])
                        ->orWhere('id',$page['info']['id'])->pluck('id')->toArray();
                    $query->whereIn('distributor_id',$distributors);
                }
            }
        })->count();
        return $this->success($data);
    }

    /**电站列表
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function jtList(RequestInterface $request):ResponseInterface
    {
        $page = $request->inputs(['page','limit','keyword','charge_id','distributor_id','is_active']);
        $page['info'] = $this->distributors->getInfo($request);
        $query = $this->station->where(function ($query) use ($page) {
            if (array_key_exists('keyword',$page) && $page['keyword']) {
                $query->where('name', 'like', '%' . $page['keyword'] . '%');
                $query->orWhere('address', 'like', '%'.$page['keyword'].'%');
            }
            if($page['is_active'] != ''){
                $query->where('is_active', $page['is_active']);
            }
            $query->where('distributor_id', 15210);
        })->with('distributors')
            ->withCount('device');
        $data['total']= $query->count();
        $data['list'] = $query->orderBy('id', 'desc')
            ->offset(($page['page'] - 1) * $page['limit'])
            ->limit($page['limit'])->get();
        return $this->success($data);
    }

    /**下拉菜单-套餐
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function selectCharge(RequestInterface $request):\Psr\Http\Message\ResponseInterface
    {
        $distributor_id = $request->input('distributor_id');
        $list = $this->chargeOption->where('distributor_id',  0)->orderBy('sort', 'desc')
            ->get(['id','name'])->toArray();
        foreach($list as $k => $v){
            $list[$k]['name'] ='[默认]'.$v['name'];
        }
         if($distributor_id){
             $distributor_id = json_decode($distributor_id);
             if(count($distributor_id) > 0 ){
                 $distributor_id = end($distributor_id);
                 $dis_list =  $this->chargeOption->where('distributor_id',  $distributor_id)->orderBy('sort', 'desc')
                     ->get(['id','name'])->toArray();
                 $list = array_merge($list,$dis_list);
             }
        }
        return $this->success($list);
    }

    public function jtStation(RequestInterface $request){
        $list =  $this->station->where('distributor_id',  15210)
            ->get(['id','name'])->toArray();
        return $this->success($list);
    }

    /**下拉菜单充电桩
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function selectStation(RequestInterface $request):\Psr\Http\Message\ResponseInterface
    {
        $info = $this->distributors->getInfo($request);
        $distributor_id = $request->input('distributor_id');
        if(!$distributor_id){
//            if($info['level'] == 1){
//                $distributors = Distributors::where('parent_id',$info['id'])
//                    ->orWhere('id',$info['id'])->pluck('id')->toArray();
//                $list =  $this->station->whereIn('distributor_id', $distributors)
//                    ->get(['id','name'])->toArray();
//            }else{
                $list =  $this->station->where('distributor_id',  $info['id'])
                    ->get(['id','name'])->toArray();
//            }
        }else{
            $distributor_id = json_decode($distributor_id);
            if(is_array($distributor_id)){
                if(count($distributor_id) > 0 ){
                    $distributor_id = end($distributor_id);
                }
            }
            $list =  $this->station->where('distributor_id',  $distributor_id)
                ->get(['id','name'])->toArray();
        }
        return $this->success($list);
    }
    /**修改状态
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function changeStatus(RequestInterface $request):ResponseInterface
    {
        $status = $request->input('status',0,'int');
        $id = $request->input('id',0,'int');
        if (!$id) {
           return $this->error(code:1001,msg:'缺失参数id');
        }
        $this->station->where('id',$id)->update(['is_active'=>$status]);
        return $this->success(msg:'修改成功');
    }


    /**获取经销商id
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function getDistributor(RequestInterface $request):ResponseInterface{
        $station_id = $request->input('station_id',0,'int');
        $distributorId = $this->station->where('id',$station_id)->first(['distributor_id']);
        return $this->success($distributorId);
    }


    /**创建电站
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function create(RequestInterface $request):\Psr\Http\Message\ResponseInterface
    {
        $data = $request->post();
        $info = $this->distributors->getInfo($request);

        if(!$data['distributor_id']){
            $data['distributor_id'] = $info['id'];
        }
        if(isset($data['distributors'])){
            unset($data['distributors']);
        }
        if(is_array($data['images'])){
            $data['images'] = json_encode($data['images']);
        }
        if (array_key_exists('id',$data) && $data['id'] > 0) {
            $id = $data['id'];
            unset($data['id']);
            if(isset($data['distributor_name'])){
                unset($data['distributor_name']);
            }
            if(isset($data['device_num'])){
                unset($data['device_num']);
            }
            if(array_key_exists('updated_at', $data)){
                unset($data['updated_at']);
            }
            $this->station->where('id', $id)->update($data);
        } else {
            Station::create($data);
        }
        return $this->success();
    }

    /**删除充电站
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function del(RequestInterface $request):\Psr\Http\Message\ResponseInterface
    {
        $id = $request->input('id',0,'int');
        if (!$id) {
            return $this->error(ErrorCode::PARAMS_ERR);
        }
        $this->station->where('id',$id)->delete();
        return $this->success();
    }

}
